import { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { queryUserList, deleteUser, saveOrUpdateUser } from '@/services/user-management';
import { Input, Button, Popconfirm, Space, message, Modal, Form } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { history } from 'umi';

import type { ProColumns, ParamsType, ActionType } from '@ant-design/pro-components';
import type { PaginationProps } from 'antd/es/pagination/Pagination';

const UserManagement: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [isModalOpen, setIsModalOpen] = useState<boolean>(false);
  const [pwdForm] = Form.useForm();
  const [rowRecord, setRow] = useState<object>({});
  /**
   * 删除
   * @param id
   */
  const deleteItem = async (id: string) => {
    const res = await deleteUser({ id });
    if (!res.code && res.data) {
      message.success('删除成功');
      actionRef.current?.reload();
    }
  };

  // 修改状态
  const handleChangeEnable = async (record: any) => {
    const params = { ...record, enable: !record?.enable ? 1 : 0 };
    const res = await saveOrUpdateUser(params);
    if (!res.code) {
      message.success('修改成功');
      actionRef.current?.reload();
    } else {
      message.error('修改失败');
    }
  };

  const handleChangePwd = (row: any) => {
    setIsModalOpen(true);
    pwdForm.setFieldValue(['username'], row?.username || row?.yumId);
    setRow(row);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const handleOk = async () => {
    const pwd = pwdForm.getFieldValue('password');
    const pwdSure = pwdForm.getFieldValue('surePassword');
    if (pwd && pwdSure && pwdSure.trim() !== pwd.trim()) {
      message.error('两次输入密码不相同，请重新输入');
      return;
    }
    const res = await saveOrUpdateUser({
      ...rowRecord,
      password: pwd,
    });
    if (!res.code) {
      message.success('修改成功');
      actionRef.current?.reload();
    } else {
      message.error('修改失败');
    }
  };

  const handleCheckPwd = (rule: any, value: string, callback: any) => {
    const pwd = pwdForm.getFieldValue('password');
    if (value === undefined || value === '') {
      callback(new Error('请输入确认密码'));
    }
    if (value && pwd && value.trim() !== pwd.trim()) {
      callback(new Error('两次输入密码不相同，请重新输入。'));
    }
    callback();
  };

  /**
   * table columns
   */
  const columns: ProColumns<API.UserItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 48,
      align: 'center',
      hideInSearch: true,
    },
    // {
    //   title: 'yumId',
    //   dataIndex: 'yumId',
    //   key: 'yumId',
    //   ellipsis: true,
    //   hideInSearch: true,
    //   align: 'center',
    // },
    {
      title: '账号',
      dataIndex: 'username',
      key: 'username',
      ellipsis: true,
      fieldProps: {
        placeholder: '请输入账号',
      },
      // align: 'center',
      render: (_, row) => {
        return <div>{row?.username || row?.yumId}</div>;
      },
    },
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
      ellipsis: true,
      align: 'center',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入角色',
      },
    },
    {
      title: '角色',
      dataIndex: 'roleDO',
      ellipsis: true,
      hideInSearch: true,
      // align: 'center',
      renderText: (roleDO: API.UserItem['roleDO']) => {
        return (roleDO && roleDO.name) || '';
      },
    },

    {
      title: '用户名称',
      dataIndex: 'nickName',
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '账号状态',
      dataIndex: 'enable',
      key: 'enable',
      ellipsis: true,
      align: 'center',
      fieldProps: {
        placeholder: '请选择账号状态',
      },
      // hideInTable: true,
      valueEnum: {
        1: { text: '启用' },
        0: { text: '禁用' },
      },
    },
    // {
    //   title: '头像',
    //   dataIndex: 'avatar',
    //   key: 'avatar',
    //   hideInSearch: true,
    //   align: 'center',
    //   render: (recode) => <Avatar size="small" src={recode} />,
    // },
    // {
    //   title: '邮箱',
    //   dataIndex: 'email',
    //   key: 'email',
    //   ellipsis: true,
    //   hideInSearch: true,
    //   align: 'center',
    // },
    // {
    //   title: '登录次数',
    //   dataIndex: 'loginTotal',
    //   key: 'loginTotal',
    //   ellipsis: true,
    //   hideInSearch: true,
    //   align: 'center',
    // },
    {
      title: '操作',
      key: 'options',
      hideInSearch: true,
      align: 'center',
      width: 250,
      // permission: ['ADMIN', 'MODULE_MANAGER'], // 按钮鉴权，暂时注释
      render: (_, row) => {
        return (
          <Space>
            <a key="link" href={`#/system/user/detail/read/${row.id}`}>
              查看
            </a>
            <a key="modify" href={`#/system/user/detail/modify/${row.id}`}>
              编辑
            </a>
            <a onClick={() => handleChangeEnable(row)}>{!row.enable ? '启用' : '禁用'}</a>
            <a onClick={() => handleChangePwd(row)}>修改密码</a>
            <Popconfirm
              key="delete"
              title="确定要删除此用户?"
              onConfirm={() => deleteItem(row.id!)}
              okText="确定"
              cancelText="取消"
              disabled={!row.enable}
            >
              <a href="#">删除</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  /**
   * 列表接口
   * @param params
   * @returns
   */
  const getUserList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: API.UserParam = {
      pageNum: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };
    const res = await queryUserList(param);
    if (!res.code && res.data) {
      const { content, totalSize, pageSize, pageNum } = res.data;
      return {
        total: totalSize,
        pageSize,
        current: pageNum,
        data: content,
      };
    }
    return [];
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;
  return (
    <PageContainer>
      <ProTable<API.UserItem>
        actionRef={actionRef}
        columns={columns}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          size: 'small',
          showTotal,
          showQuickJumper: true,
        }}
        request={getUserList}
        options={false}
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => history.push('/system/user/detail/add')}
          >
            新增用户
          </Button>,
        ]}
      />
      <Modal title="修改密码" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form labelCol={{ span: 5 }} form={pwdForm} name="pwdForm">
          <Form.Item label="账号" name="username">
            <Input disabled={true} />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              {
                min: 6,
                message: '密码长度6-22个字符',
              },
              {
                max: 22,
                message: '密码长度6-22个字符',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            label="确认密码"
            name="surePassword"
            rules={[
              { required: true, message: '请确认密码并保持密码一致!', validator: handleCheckPwd },
              {
                min: 6,
                message: '密码长度6-22个字符',
              },
              {
                max: 22,
                message: '密码长度6-22个字符',
              },
            ]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default UserManagement;
